﻿using Furion.DatabaseAccessor;
using Furion.DatabaseAccessor.Extensions;
using Furion.DependencyInjection;
using Furion.DynamicApiController;
using Furion.FriendlyException;
using LimaLims.Application.Service.Base.Dto;
using LimaLims.Application.Service.Basic.Dto;
using LimaLims.Application.Service.Sys;
using LimaLims.Core;
using LimaLims.Core.Entity.Basic;
using LimaLims.Core.Entity.TestCenter;
using LimaLims.Core.Enum;
using LimaLims.Core.Util;
using Mapster;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;

namespace LimaLims.Application.Service.Basic
{
    /// <summary>
    /// 物料服务
    /// </summary>
    [ApiDescriptionSettings(Name = "Material", Order = 154)]
    [Route("api")]
    public class MaterialService : IMaterialService, IDynamicApiController, ITransient
    {
        private readonly IRepository<Material> _materialRep;  // 物料表仓储
        private readonly IRepository<ExperimentTask> _experimentTaskRep;
        private readonly IGenerateCodeUtilService _generateCodeUtilService;//编码规则

        public MaterialService(IRepository<Material> materialRep, IRepository<ExperimentTask> experimentTaskRep,IGenerateCodeUtilService generateCode)
        {
            _materialRep = materialRep;
            _experimentTaskRep = experimentTaskRep;
            _generateCodeUtilService = generateCode;
        }

        /// <summary>
        /// 新增
        /// </summary>
        [HttpPost("material/add")]
        public async Task Add(AddMaterialInput input)
        {
            var isExist = await _materialRep.DetachedEntities.AnyAsync(u => u.Name == input.Name && u.Code == input.Code);
            if (isExist)
                throw Oops.Oh("已存在相同名称和编号的物料！");

            if (string.IsNullOrWhiteSpace(input.Code))
            {
                input.Code = await _generateCodeUtilService.GenerateCode(BusinessType.Material);
            }

            var product = input.Adapt<Material>();

            await product.InsertAsync();
        }

        [HttpPost("material/delete")]
        public async Task Delete(long id)
        {
            var product = await _materialRep.FirstOrDefaultAsync(u => u.Id == id);
            if (product == null)
                throw Oops.Oh("不存在此数据");

            var tasks = _experimentTaskRep.DetachedEntities.Count(s => s.TargetId == product.Id);

            if (tasks > 0)
                throw Oops.Oh("此物料已关联试验任务信息，请勿直接删除！");

            await product.DeleteAsync();
        }

        [HttpGet("material/detail")]
        public async Task<Material> Detail(long id)
        {
            var product = await _materialRep.DetachedEntities.FirstOrDefaultAsync(u => u.Id == id);
            if (product == null)
                throw Oops.Oh("不存在此数据");

            return product;
        }

        [HttpPost("material/edit")]
        public async Task Edit(EditMaterialInput input)
        {
            var product = await _materialRep.DetachedEntities.FirstOrDefaultAsync(u => u.Id == input.Id);
            if (product == null)
                throw Oops.Oh("不存在此数据！");

            var isExist = await _materialRep.DetachedEntities.AnyAsync(u => u.Name == input.Name && u.Code == input.Code && u.Id != input.Id);
            if (isExist)
                throw Oops.Oh("已存在相同名称和编号的物料！");

            var productModel = input.Adapt<Material>();

            await productModel.UpdateAsync();
        }

        /// <summary>
        /// 下拉数据
        /// </summary>
        /// <returns></returns>
        [HttpGet("material/selectList")]
        public async Task<List<SelectDto>> SelectList()
        {
            var list = await _materialRep.DetachedEntities.Where(s => s.ValidStatus).OrderBy(s => s.Sort).ToListAsync();
            return list.Select(x => new SelectDto
            {
                Value = x.Id,
                Label = $"{x.Code}-{x.Name}"
            }).ToList();
        }

        [HttpGet("material/page")]
        public async Task<PageResult<MaterialOutput>> QueryPage([FromQuery] MaterialPageInput input)
        {
            var name = !string.IsNullOrEmpty(input.SearchValue?.Trim());
            var code = !string.IsNullOrEmpty(input.Code?.Trim());
            var items = await _materialRep.DetachedEntities.Include(s=>s.Supplier)
                                         .Where((name, u => EF.Functions.Like(u.Name, $"%{input.SearchValue.Trim()}%")))
                                         .Where((code, u => EF.Functions.Like(u.Code, $"%{input.Code.Trim()}%")))
                                         .Where(input.ValidStatus.HasValue, u => u.ValidStatus == input.ValidStatus)
                                         .OrderBy(u => u.Sort)
                                         .Select(u => new MaterialOutput
                                         {
                                             Id = u.Id,
                                             Code = u.Code,
                                             Name = u.Name,
                                             Specification = u.Specification,
                                             Unit = u.Unit,
                                             SupplierId = u.SupplierId,
                                             SupplierName=u.Supplier.Name,
                                             Remark = u.Remark,
                                             ValidStatus = u.ValidStatus,
                                             Sort = u.Sort,
                                             CreatedTime = u.CreatedTime,
                                             CreatedUserName = u.CreatedUserName,
                                             UpdatedTime = u.UpdatedTime,
                                             UpdatedUserName = u.UpdatedUserName
                                         }).ToADPagedListAsync(input.PageNo, input.PageSize);

            return items;
        }
    }
}
